//
//  RentModelManager.m
//  RentTable
//
//  Created by xchuan xchuan on 2024/12/2.
//

#import "RentModelManager.h"

@implementation RentModelManager

+ (void)saveRentModels:(NSArray<RentModel *> *)models {
    NSMutableArray *existingModels = [[self loadRentModels] mutableCopy];
    if (!existingModels) {
        existingModels = [NSMutableArray array];
    }

    NSMutableArray *dictArray = [NSMutableArray array];
    for (RentModel *model in existingModels) {
        [dictArray addObject:[model toDictionary]]; // 添加已有模型
    }
    
    for (RentModel *newModel in models) {
        [dictArray addObject:[newModel toDictionary]];
    }

    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dictArray requiringSecureCoding:NO error:nil];
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"rentModels"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (NSArray<RentModel *> *)loadRentModels {
    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"rentModels"];
    if (data) {
        NSArray *dictArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        NSMutableArray *models = [NSMutableArray array];
        for (NSDictionary *dict in dictArray) {
            RentModel *model = [[RentModel alloc] initWithDictionary:dict];
            [models addObject:model];
        }
        return models;
    }
    return nil;
}

+ (void)removeRentModelByRentBuyId:(NSInteger)rentBuyId {
    NSMutableArray *models = [[self loadRentModels] mutableCopy];
    if (models) {
        RentModel *modelToRemove = nil;
        for (RentModel *model in models) {
            if (model.rentBuyId == rentBuyId) {
                modelToRemove = model;
                break;
            }
        }
        
        if (modelToRemove) {
            [models removeObject:modelToRemove];
            [self RemoveRentModels:models];
        }
    }
}

+ (void)RemoveRentModels:(NSArray<RentModel *> *)models {
    NSMutableArray *dictArray = [NSMutableArray array];
    for (RentModel *model in models) {
        [dictArray addObject:[model toDictionary]];
    }
    
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dictArray requiringSecureCoding:NO error:nil];
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"rentModels"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}


@end
